/**   
 * @Title: RegistAct.java 
 * @Package com.esun.rabbit2.viewer 
 * @Description: (注册activity) 
 * @author City Jiangsy@500wan.com   
 * @date 2011-6-8 下午07:56:28  
 * copy right 深圳市易讯天空网络技术有限公司
 */
package com.esun.rabbit2.viewer;

import com.esun.config.Config;
import com.esun.config.Language;
import com.esun.model.UserInfo;
import com.esun.network.ConnectionChangeReceiver;
import com.esun.network.communicater.UserCommunicater;
import com.esun.ui.R;
import com.esun.util.StringUtil;
import com.esun.util.ViewerUtil;
import com.esun.util.log.EDebug;
import com.esun.util.md5.MD5;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.ContentValues;
import android.content.Intent;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.Html;
import android.text.method.LinkMovementMethod;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.CompoundButton.OnCheckedChangeListener;

/**
 * @ClassName: RegistAct
 * @Description: (用户注册activity)
 * @author City Jiangsy@500wan.com
 * @date 2011-6-8 下午07:56:28
 * 
 */
public class RegistAct extends Activity implements OnCheckedChangeListener, OnClickListener {
	private Intent regIntent;

	private Button btnRegist; // 注册按钮
	private Button btnBack; // 返回..
	private Button btnCleanUserName; // 清空用户名
	private Button btnCleanUserPass; // 清空密码
	private Button btnCleanUserPhoneNum; // 清空手机号

	private EditText edtUserName; // 用户名
	private EditText edtUserPass; // 密码
	private EditText edtUserPhoneNum; // 手机号
	private TextView tvUserAgree; // 用户条款

	private String strUserName;
	private String strUserPass;
	private String strUserPhoneNum;

	private CheckBox cbxUserAgree; // 确认同意用户条款

	private Handler registHandler;

	private ProgressDialog registProgressDialog;

	private String strServerMsg; // 存放服务器返回信息

	private UserCommunicater userCommunicater;

	private final int REGIST_SUCCEED = 1001; // 标志位,注册成功
	private final int REGIST_FAIL = 1002; // ..注册失败
	private final int LOGIN_SUCCEED = 1003; // ..登陆成功
	private final int LOGIN_FAIL = 1004; // ..登陆失败

	public static boolean isRegistSucceed = false;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.regist_act);
		regIntent = new Intent().setClass(RegistAct.this, LoginAct.class);
		userCommunicater = new UserCommunicater();
		uiInit();
		handlerInit();
	}

	private void uiInit() {
		btnRegist = (Button) findViewById(R.id.registact_btn_regist);
		btnRegist.setOnClickListener(this);
		btnBack = (Button) findViewById(R.id.registact_btn_back);
		btnBack.setOnClickListener(this);
		btnCleanUserName = (Button) findViewById(R.id.registact_btn_claenUserNmae);
		btnCleanUserName.setOnClickListener(this);
		btnCleanUserPass = (Button) findViewById(R.id.registact_btn_claenUserPass);
		btnCleanUserPass.setOnClickListener(this);
		btnCleanUserPhoneNum = (Button) findViewById(R.id.registact_btn_claenUserPhone);
		btnCleanUserPhoneNum.setOnClickListener(this);

		edtUserName = (EditText) findViewById(R.id.registact_edt_userName);
		edtUserPass = (EditText) findViewById(R.id.registact_edt_userPass);
		edtUserPhoneNum = (EditText) findViewById(R.id.registact_edt_userPhone);

		cbxUserAgree = (CheckBox) findViewById(R.id.registact_cbx_userAgree);
		cbxUserAgree.setOnCheckedChangeListener(this);
		cbxUserAgree.setChecked(true);

		tvUserAgree = (TextView) findViewById(R.id.registact_tv_userAgree);
		tvUserAgree.setText(Html.fromHtml("<a href=\"http://3g.500wan.com/help/terms.jsp\">《500WAN服务条款》</a>"));

		tvUserAgree.setMovementMethod(LinkMovementMethod.getInstance());

		registProgressDialog = ViewerUtil.showProgressDialog(this, "注册中...");
	}

	private void handlerInit() {
		registHandler = new Handler() {
			@Override
			public void handleMessage(Message msg) {
				switch (msg.what) {

				case REGIST_SUCCEED:
					// 注册成功后调用登陆
					threadLogin();
					break;

				case REGIST_FAIL:
					registProgressDialog.dismiss();
					ViewerUtil.showTipDialog(RegistAct.this, strServerMsg, false);
					break;

				case LOGIN_SUCCEED:
					UserInfo.getUserInfo().setUserName(strUserName);
					UserInfo.getUserInfo().setUserPwd(strUserPass);
					UserInfo.getUserInfo().setInputPasswordTime();
					updateDBInfo();
					UserInfo.getUserInfo().setSaveData(false);
					userCommunicater.updataUserInfo();
					EDebug.o(RegistAct.this, "UserInfo is changed&&userName = " + UserInfo.getUserInfo().getUserName() + " userPass = " + UserInfo.getUserInfo().getUserPwd() + " isSaved = "
							+ UserInfo.getUserInfo().isSaveData() + UserInfo.getUserInfo().getUserBalance() + UserInfo.getUserInfo().getUserFreeze());
					registProgressDialog.dismiss();
					// ViewerUtil.showTipDialog(RegistAct.this, "注册成功,已为您登陆", true);
					Toast.makeText(RegistAct.this, UserInfo.getUserInfo().getUserName() + ",您已登录成功", Toast.LENGTH_SHORT).show();
					isRegistSucceed = true;
					RegistAct.this.finish();
					break;

				case LOGIN_FAIL:
					registProgressDialog.dismiss();
					ViewerUtil.showTipDialog(RegistAct.this, "登陆错误,请手动登陆", true);
					break;

				case Config.CONNECTION_FAIL:
					registProgressDialog.dismiss();
					
					ViewerUtil.showTipDialog(RegistAct.this, Language.STR_CONNECTIONFAIL, false);
					Toast.makeText(RegistAct.this, Language.STR_CONNECTIONFAIL.toString(),Toast.LENGTH_SHORT).show();
					break;

				default:
					break;
				}
			}
		};
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.registact_btn_regist:
			// test
			EDebug.o(this, "用户输入用户名长度----unicode编码为：" + edtUserName.getText().toString() + "gbk编码长度为：" + StringUtil.getStringLengthChar(edtUserName.getText().toString()));
			// 验证输入限制条件
			if (!edtUserName.getText().equals(null) && edtUserName.getText().toString().length() < 1) {
				ViewerUtil.showTipDialog(this, "用户名不能为空", false);
			} else if (!edtUserPass.getText().equals(null) && edtUserPass.getText().toString().length() < 1) {
				ViewerUtil.showTipDialog(this, "请输入注册密码", false);
			} else if (!edtUserPhoneNum.getText().equals(null) && edtUserPhoneNum.getText().toString().length() < 1) {
				ViewerUtil.showTipDialog(this, "请输入手机号码", false);
			} else if (!(edtUserPhoneNum.getText().toString().length() == 11)) {
				// 暂定验证手机号长度为11位
				ViewerUtil.showTipDialog(this, "请输入正确的手机号码", false);
			} else if (StringUtil.getStringLengthChar(edtUserName.getText().toString()) < 4 || StringUtil.getStringLengthChar(edtUserName.getText().toString()) > 16) {
				ViewerUtil.showTipDialog(this, "用户名为4-16个字符，可以使用汉字、数字、字母", false);
			} else if (edtUserPass.getText().toString().length() < 6 || edtUserPass.getText().toString().length() > 15) {
				ViewerUtil.showTipDialog(this, "密码为6-15个字符，建议使用字母、数字组合，混合大小写", false);
			} else {
				strUserName = edtUserName.getText().toString();
				strUserPass = edtUserPass.getText().toString();
				strUserPhoneNum = edtUserPhoneNum.getText().toString();
				registProgressDialog.show();
				threadRegist();
			}
			break;

		case R.id.registact_btn_back:
			startActivity(regIntent);
			RegistAct.this.finish();
			break;

		case R.id.registact_btn_claenUserNmae:
			edtUserName.setText(Config.NULLMARK);
			break;

		case R.id.registact_btn_claenUserPass:
			edtUserPass.setText(Config.NULLMARK);
			break;

		case R.id.registact_btn_claenUserPhone:
			edtUserPhoneNum.setText(Config.NULLMARK);
			break;

		default:
			break;
		}

	}

	// 子进程,注册
	private void threadRegist() {
		new Thread() {
			@Override
			public void run() {
				super.run();
				try {
					boolean registSucceed = userCommunicater.isRegisterSucceed(strUserName, strUserPass, strUserPhoneNum);
					strServerMsg = userCommunicater.getMsgServer();
					if (registSucceed) {
						Message msg = registHandler.obtainMessage(REGIST_SUCCEED, null);
						registHandler.sendMessage(msg);
					} else {
						Message msg = registHandler.obtainMessage(REGIST_FAIL, null);
						registHandler.sendMessage(msg);
					}
				} catch (Exception e) {
					Message msg = registHandler.obtainMessage(Config.CONNECTION_FAIL, null);
					registHandler.sendMessage(msg);
				}
			}
		}.start();
	}

	// 子进程,登录
	private void threadLogin() {
		new Thread() {
			@Override
			public void run() {
				super.run();
				if (strUserPass.length() != 32) {
					strUserPass = MD5.md5(strUserPass);
				}
				try {
					boolean loginSucceed = userCommunicater.isLoginSucceed(strUserName, strUserPass);
					strServerMsg = userCommunicater.getMsgServer();
					if (loginSucceed) {
						Message msg = registHandler.obtainMessage(LOGIN_SUCCEED, null);
						registHandler.sendMessage(msg);
					} else {
						Message msg = registHandler.obtainMessage(LOGIN_FAIL, null);
						registHandler.sendMessage(msg);
					}
				} catch (Exception e) {
					Message msg = registHandler.obtainMessage(Config.CONNECTION_FAIL, null);
					registHandler.sendMessage(msg);
				}
			}
		}.start();
	}

	@Override
	public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
		switch (buttonView.getId()) {
		case R.id.registact_cbx_userAgree:
			if (isChecked) {
				btnRegist.setEnabled(true);
			} else {
				btnRegist.setEnabled(false);
			}
			break;

		default:
			break;
		}
	}

	// 返回键功能设置
	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {

		// 捕捉返回键动作
		if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0) {
			startActivity(regIntent);
			RegistAct.this.finish();
			return true;
		}
		return false;
	}

	private static final String NAME = "name"; // 表元素,用户名
	private static final String PWD = "password"; // ..密码
	private static final String SAVE = "save"; // ..是否保存用户信息

	private static final String DBNAME = "db_arabbit2"; // 数据库名
	private static final String TABLENAME = "users"; // 表名

	private void updateDBInfo() {
		// user TEXT,password TEXT,save TEXT
		EDebug.o(this, "updateDBInfo");
		ContentValues cv = new ContentValues();
		cv.put(NAME, strUserName);
		cv.put(PWD, strUserPass);
		cv.put(SAVE, Config.NUM1);

		SQLiteDatabase db = this.openOrCreateDatabase(DBNAME, MODE_PRIVATE, null);
		db.update(TABLENAME, cv, "_id=?", new String[] { Config.NUM1 });
		db.close();
	}

	@Override
	protected void onPause() {
		super.onPause();
		this.unregisterReceiver(ConnectionChangeReceiver.getConnectionChangeReceiver());
	}

	@Override
	protected void onResume() {
		super.onResume();
		this.registerReceiver(ConnectionChangeReceiver.getConnectionChangeReceiver(), ConnectionChangeReceiver.getIntentFilter());
	}
}
